package pct.group;

import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import pct.database.PcServiceImpl;
import pct.entity.Group;
import pct.manage.StatusManager;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

@SuppressWarnings({ "serial", "rawtypes" })
public class ApplyNewGroup extends ActionSupport implements ModelDriven,
		Preparable, SessionAware {
	private Group group = new Group();
	private PcServiceImpl pcService = new PcServiceImpl();
	private Map<String, Object> session;

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	@Override
	public void prepare() throws Exception {
		pcService.connectDB();
	}

	@Override
	public Object getModel() {
		return group;
	}

	public Group getGroup() {
		return group;
	}

	public void setGroup(Group group) {
		this.group = group;
	}
	
	public String execute() {
		StatusManager sm = (StatusManager) session.get("status");
		pcService.applyNewGoup(group, sm.getCurrentUser());
		return SUCCESS;
	}
	
	public void validate() {
		if(pcService.groupExists(group)) {
			addFieldError("groupName", "Group already exits.");
		}
	}
}
